<template>
  <view class="container">
    <u-navbar :is-back="true" :title="navbarTitle" :border="false"></u-navbar>
    <view class="wrapper01">
      <view class="charts-box">
        <qiun-data-charts type="ring" :opts="opts" :chartData="chartData" />
      </view>
    </view>
    <view class="spacing"></view>
    <view class="wrapper02">
      <view class="title">{{ title }}</view>
      <view class="card-container">
        <u-cell-group>
          <u-cell-item
            v-for="(item, index) in cellData"
            :key="index"
            :title="item.name"
            :value="item.value + '道'"
            :arrow="true"
            arrow-direction="right"
            @click="handleCellClick(item)"
          >
          </u-cell-item>
        </u-cell-group>
        <view class="empty-space" v-if="cellData.length === 0"></view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserProfile } from "@/api/system/user";
import { allUserquestionss } from "@/api/business/userquestions";

export default {
  data() {
    return {
      chartData: {},
      type: 1, // 默认值
      title: '', // 标题
      navbarTitle: '我的错题', // Navbar标题
      cellData: [], // 单元格内容将由后端数据填充
      userId: null, // 当前用户ID
      questionIds: [] // 存储问题ID
    };
  },
  onLoad(e) {
    this.type = e.atype ? parseInt(e.atype) : 1;
    this.setTitleBasedOnType();
    this.getUserProfile(); // 获取当前用户信息
  },
  methods: {
    setTitleBasedOnType() {
      if (this.type === 1) {
        this.title = "错题分类";
        this.navbarTitle = "我的错题"; // 设置 Navbar 标题
      } else if (this.type === 2) {
        this.title = "收藏分类";
        this.navbarTitle = "我的收藏"; // 设置 Navbar 标题
      } else {
        this.title = "未知分类"; // 处理其他情况
        this.navbarTitle = "未知分类"; // 设置 Navbar 标题
      }
    },
    async getUserProfile() {
      try {
        const response = await getUserProfile();
        this.userId = response.data.userId; // 假设返回的数据中有 userId
        this.getServerData(); // 获取数据
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    async getServerData() {
      try {
        const query = { user_id: this.userId }; // 用户ID
        if (this.type === 1) {
          query.status = 1; // 只查询 status=1 的数据
        } else if (this.type === 2) {
          query.star = 0; // 只查询 star=0 的数据
        }
        const response = await allUserquestionss(query); // 修改为 allUserquestions
        if (response && response.data && Array.isArray(response.data)) {
          this.processData(response.data);
        } else {
          console.error('返回的数据格式不正确:', response);
          uni.showToast({
            title: '系统发生错误，请联系管理员',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取题目信息失败:', error);
        uni.showToast({
          title: '系统发生错误，请联系管理员',
          icon: 'none'
        });
      }
    },
    processData(data) {
        const typeCountMap = {
			6: { name: "政治理论", value: 0, ids: [] },
            1: { name: "常识判断", value: 0, ids: [] },
            2: { name: "数量关系", value: 0, ids: [] },
            3: { name: "判断推理", value: 0, ids: [] },
            4: { name: "资料分析", value: 0, ids: [] },
            5: { name: "言语理解与表达", value: 0, ids: [] }
        };
    
        data.forEach(item => {
            if (typeCountMap[item.type]) {
                typeCountMap[item.type].value += 1; // 按类型统计数量
                typeCountMap[item.type].ids.push(item.questionId); // 存储 question_id
            } else {
                console.warn(`未知题型: ${item.type}`); // 处理未知题型
            }
        });
    
        this.cellData = Object.values(typeCountMap); // 转换为数组格式
    
        // 计算总题目数量
        const totalCount = this.cellData.reduce((total, item) => total + item.value, 0);
    
        // 更新图表数据
        this.chartData = {
            series: [
                {
                    data: this.cellData.map(item => ({
                        name: item.name,
                        value: item.value / totalCount * 100 // 计算百分比
                    })),
                    format: 'noPointNumber'
                }
            ]
        };
    },
    handleCellClick(item) {
	  // 检查单元格的 value 是否为 0
	      if (item.value === 0) {
	        // 弹窗提示
	        uni.showToast({
	          title: '还没有题目哦',
	          icon: 'none'
	        });
	        return; // 终止后续操作
	      }
		
      // 处理单元格点击事件，获取对应题目ID并跳转
      const questionIds = item.ids; // 获取对应类型的题目ID数组
      
      // 打乱顺序
      const shuffledQuestionIds = this.shuffleArray(questionIds);
      
      // 跳转到 paper.vue 页面并传递题目ID数组
      uni.navigateTo({
        url: `/subPackageA/paper?questionIds=${JSON.stringify(shuffledQuestionIds)}`
      });
    },
    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.charts-box {
  width: 100%;
  height: 200px;
}

.wrapper01 {
  pointer-events: none;
  height: 200px;
  background-color: #ffffff;
  border-radius: 0 0 35rpx 35rpx;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.spacing {
  height: 20px;
  background-color: transparent;
}

.wrapper02 {
  background-color: #ffffff;
  border-radius: 35rpx 35rpx 0 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 22px;
  padding: 4px;
  font-weight: bold;
  margin-bottom: 10px;
}

.empty-space {
  flex-grow: 1;
}
</style>
